/**
 * 2018年12月21日下午4:31:24
 * @author 谢进财
 */
package com.baihang.project.ds.webSocket.controller;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

import com.baihang.framework.controller.BaseController;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.project.ds.config.SystemConfig;
import com.baihang.project.ds.webSocket.handler.DsWebSocketHandler;
import com.baihang.project.ds.webSocket.service.WebSocketService;

import redis.clients.jedis.Jedis;

/**
 * @author whati
 *
 */
@Controller
@RequestMapping("/webSocket")
public class WebSocketController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(WebSocketController.class);
	private Jedis jedis = RedisKit.getJedis();
	@Autowired
	private DsWebSocketHandler handler;
	@Autowired
	private WebSocketService service;
	@RequestMapping
	public String index() {
		return "/project/ds/websocket/index";
	}
	
	@ResponseBody
    @RequestMapping(value = "/broadcast", method = RequestMethod.GET)
    public void broadcast() throws IOException {
        System.err.println("群发");
        handler.broadcast(new TextMessage("123"));
    } 
	
	/**
	 * 修改单个配置
	 * @param key
	 * @param value
	 * @return
	 */
	@ResponseBody
	@PostMapping("/changeSystemConfig")
	public String changeSystemConfig(String key,String value) {
		logger.info("key:{},value:{}",key,value);
		if(SystemConfig.configMap.containsKey(key)) {
			SystemConfig.configMap.put(key, value);
		}
		return "ok";
	}
	
	/**
	 * 根据传入的json改变所有配置，改变内存中的配置
	 * @param json
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/changeSystemConfigs")
	public String changeSystemConfigs(String json) {
		logger.info("json={}",json);
		service.changeSystemConfigs(json);
		return "ok";
	}*/
	
	@ResponseBody
    @RequestMapping(value = "/houseStateControl", method = RequestMethod.POST)
    public void houseStateControl(String msg) throws IOException {
		String jsonResult = String.format("{\"code\":\"%s\",\"result\":\"%s\"}","002",msg);
		//SystemConfig.configMap.put("State", msg);//状态也改一下
		if("0".equals(msg)) {//项目全部结束时，清空资源
			logger.info("项目关闭");
			//清空session
			/*  DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
		      DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
		      Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
		      sessions.clear();*/
		      //清空websocketsession
		      handler.closeCommond=true;
		      handler.broadcast(new TextMessage(jsonResult));
		      //在线用户在redis中清空
		      jedis.del("zaixiang");
		}else {
			
			handler.broadcast(new TextMessage(jsonResult));
		}
    } 
	
	@ResponseBody
	@RequestMapping(value = "/userGetOut", method = RequestMethod.POST)
	public String userGetOut(String tel) throws IOException {
		logger.info("开始踢手机号为{}的用户",tel);
		String jsonResult = String.format("{\"code\":\"%s\",\"result\":\"%s\"}","003","帐号被锁定");
		handler.sendMessageToUser(tel,new TextMessage(jsonResult));
		return JsonKit.toSingleJson("true");
	} 
	
	/**
	 * 重置客户端，时间调整
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/resetClien", method = RequestMethod.POST)
	public String resetClien() {
		logger.info("开始重置客户端");
		Map<String,String> sysConfig = jedis.hgetAll("systemConfig");
		String json = JsonKit.toJson(sysConfig);
		logger.info(json);
		String jsonResult = String.format("{\"code\":\"%s\",\"result\":%s}","005",json);
		try {
			handler.broadcast(new TextMessage(jsonResult));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return JsonKit.toSingleJson("true");
	} 
}
